import 'package:flutter/material.dart';
import 'package:flutter_module/api/personal_request.dart';
import 'package:flutter_module/common/base/base_page.dart';
import 'package:flutter_module/model/transaction_list_mo.dart';
import 'package:flutter_module/model/transaction_mo.dart';

import 'item/transaction_record_item.dart';

/// Create by kyluzoi
/// Date: 2021-08-09
///
/// Description:  交易记录页面

class TransactionRecordPage extends BaseStateFulWidget {
  // const TransactionRecordPage({Key key}) : super(key: key);

  @override
  BaseState<StatefulWidget> buildState() {
    return _TransactionRecordPageState();
  }
}

class _TransactionRecordPageState extends BaseState<TransactionRecordPage>
    with BasePage {
  TransactionListMo? transactionListMo;

  ScrollController _scrollController = ScrollController();
  bool _isRefresh = true;
  bool _isLoadMore = false;
  int pageIndex = 1;

  List<TransactionMo>? transactions;

  @override
  void initState() {
    isLoading = true;
    _loadData(needCached: false);
    super.initState();
  }

  int pageSize = 10;

  void _loadData({bool needCached = false}) async {
    TransactionRecordRequest request = new TransactionRecordRequest();
    request.addQurey("pageNum", 1);
    request.addQurey("pageSize", pageSize);
    request.request(
      this,
      (result) {
        setState(
          () {
            isLoading = false;
            transactionListMo = TransactionListMo.fromJson(result);
            if (transactions != null && pageIndex != 1) {
              if (transactionListMo != null) {
                transactions?.addAll(transactionListMo!.data);
              }
            } else {
              transactions = transactionListMo!.data;
            }
          },
        );
      },
    );
  }

  @override
  Widget createView(BuildContext context) {
    return _content;
  }

  Widget get _content {
    return RefreshIndicator(
      color: Color(0xffd44949),
      onRefresh: _handleRefresh,
      child: MediaQuery.removePadding(
          removeTop: true,
          context: context,
          child: ListView.builder(
            controller: _scrollController,
            itemCount: transactions?.length ?? 0,
            padding: EdgeInsets.only(bottom: 60),
            itemBuilder: (BuildContext context, int index) =>
                TransactionRecordItem(
              index: index,
              item: transactions![index],
            ),
          )),
    );
  }

  Future<Null> _handleRefresh() async {
    _loadData();
    return null;
  }

  @override
  String get appBarTitle => '交易记录';
}
